/* $RCSFile: CRMImageBookAdd.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/PageModules/CRMImageBook/CRMImageBookAdd.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:56:46  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Globalization;

using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Helpers;
using AddonNice.UI;
using AddonNice.PageModules;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.CRMWrapper;
using AddonNice.Security;
using AddonNice.CRMWrapper.CRMImage;

using AddonNice.CRMImage;
using AddonNice.CRMImage.UI;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CRMImage
{
	/// <summary>
	/// AddonNice Portal CRMImageBook module - Usage for this page is adding new images from ,library or from
    /// new images from the PC or from a special directory on the server
    /// </summary>
    public partial class CRMImageBookAdd : AddEditImagePage
	{

        /// <summary>
        /// Fill the caegory combobox with values from the CRM image pickList
        /// </summary>
        void FillCatCombo()
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookAdd FillCatCombo BEG.",CrmImageTrace.Sw.Info);
            ADNDynImage im               =   new ADNDynImage(Wrapper,Guid.Empty);// no image entity soo set Guid.Empty
            ArrayList ar                =   im.CategoryList;
            RadComboCat.DataSource      =   ar;
            RadComboCat.DataValueField  = "val";
            RadComboCat.DataTextField   = "name";
            RadComboCat.DataBind();
            if ( RadComboCat.Items.Count > 0 )
                RadComboCat.Items[0].Selected   =   true;
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd FillCatCombo END count: {0}.",RadComboCat.Items.Count ),CrmImageTrace.Sw.Info);
        }

        /// <summary>
		/// The Page_Load event on this Page is used to obtain the ModuleID
		/// and ItemCrmID of the CRMImageBook to edit.
		///
		/// It then uses the AddonNice.CRMImageDB() data component
		/// to populate the page's edit controls with the CRMImageBook details.
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e) 
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd Page_Load BEG IsPostBack: {0}",IsPostBack ),CrmImageTrace.Sw.Info);
			if ( !IsPostBack ) 
			{
                MetadataXml                     =   Metadata.OuterXml;
                if (moduleSettingsDic[ImStr.AllowBulkLoad].ToBool())
                {
                    // they are adding, and we are allowed to bulk load so
                    // make the controls visible
                    BulkDir.Visible = true;
                    BulkDirLiteral.Visible = true;
                }
                else
                {
                    BulkDir.Visible                 =   false;				// make bulk load controls not visible for now
                    BulkDirLiteral.Visible          =   false;
                    RadTabStrip2.Tabs.Remove(RadTabStrip2.Tabs[1]);
                }
                FillCatCombo();
			}
			else
			{
                if ( !string.IsNullOrEmpty(MetadataXml) )
				    Metadata.LoadXml(MetadataXml);
			}			
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookAdd Page_Load END.",CrmImageTrace.Sw.Info);
		}

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add(ImStr.CRMImageBookGuid.Trim(new char[]{'{','}'}));
				return al;
			}
		}

		/// <summary>
		/// We need to be able to override the demo license to let enter a limited number of images
		/// </summary>
        protected override void OnUpdate(ADNPageEventArgs e) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose || CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd OnUpdate BEG IsDemo: {0}.",IsDemo),
                    ( PageTraceSwitch.Sw.TraceVerbose) ? PageTraceSwitch.Sw.Info:CrmImageTrace.Sw.Info);
            // Demo version no update
            if ( IsDemo )
            {
                e.OverrideDemo = true;
            }
            base.OnUpdate(e);
            if ( PageTraceSwitch.Sw.TraceVerbose || CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookAdd OnUpdate END.",( PageTraceSwitch.Sw.TraceVerbose) ? PageTraceSwitch.Sw.Info:CrmImageTrace.Sw.Info);
        }

        /// <summary>
		/// The Update event on this Page is used to either
		/// add an image to a CRMImageBook 
        /// If tabStrip specify to choose from collection it calls the custom ImageBookSelect
        /// Else it creates a new image, add it to library and add it to the imageBook
		/// </summary>  
        void CRMImageBookAdd_Update(object sender, ADNPageEventArgs e)
		{
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update BEG RadTabStrip1.SelectedIndex : {0}", RadTabStrip1.SelectedIndex),CrmImageTrace.Sw.Info);
            string ImFormat     =   portalSettings.CustomSettings[ImStr.ImageFormat].Value;
            ImageFormat fmt     =   ( ImFormat == "Jpeg" ) ? ImageFormat.Jpeg:ImageFormat.Png;
            string imExt        =   ( ImFormat == "Jpeg" ) ? "jpg":"png";

            if ( RadTabStrip1.SelectedIndex == 1 )
            {
                //Get the resize option for the thumbnail
                PicResizeOption thumbnailResize =
                    (!moduleSettingsDic.ContainsKey(ImStr.ThumbnailResize) || moduleSettingsDic[ImStr.ThumbnailResize].Value == string.Empty) 
                                ? PicResizeOption.FixedWidthHeight :
                                    (PicResizeOption)moduleSettingsDic[ImStr.ThumbnailResize].ToInt();
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update thumbnailResize: {0}", thumbnailResize),CrmImageTrace.Sw.Info);

                //Get the resize option for the original CRMImageBook
                PicResizeOption originalResize =
                    (!moduleSettingsDic.ContainsKey(ImStr.OriginalResize) ||
                    moduleSettingsDic[ImStr.OriginalResize].Value == string.Empty) ? PicResizeOption.NoResize :
                    (PicResizeOption)moduleSettingsDic[ImStr.OriginalResize].ToInt();
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update originalResize: {0}", originalResize),CrmImageTrace.Sw.Info);

                //Dimensions of the thumbnail as specified in settings
                int thumbnailWidth  = (int)moduleSettingsDic[ImStr.ThumbnailWidth].ToUnit().Value;
                int thumbnailHeight = (int)moduleSettingsDic[ImStr.ThumbnailHeight].ToUnit().Value;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update thumbnailWidth: {0}, thumbnailHeight: {0}", thumbnailWidth,thumbnailHeight),CrmImageTrace.Sw.Info);

                //Dimensions of the original CRMImage as specified in settings
                int originalWidth   = (int)moduleSettingsDic[ImStr.OriginalWidth].ToUnit().Value;
                int originalHeight  = (int)moduleSettingsDic[ImStr.OriginalHeight].ToUnit().Value;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update originalWidth: {0}, originalHeight: {0}", originalWidth,originalHeight),CrmImageTrace.Sw.Info);

                int displayOrder = 0;
                try
                {
                    if ( Order.Value.HasValue )
                        displayOrder = (int)Order.Value.Value;
                }
                catch(Exception ex)
                { 
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update displayOrder : {0}, ex :{1}", Order, ex),CrmImageTrace.Sw.Info);
                }

                // get the category
                int Category                    =   int.Parse(RadComboCat.SelectedValue);

                // See if they are doing a bulk load.  They must have specified
                // a bulk load directory (which is on the server) and they must not
                // have specified a specific upload file name, and they must not be editing an item.
                if ( RadUpload1.UploadedFiles.Count == 0 &&
                        !string.IsNullOrEmpty(BulkDir.Text))
                {
                    string bulkfmt          =   Server.HtmlDecode(Server.HtmlEncode(BulkFormat.Text));
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update BulkUpload BulkDir: '{0}', Caption: '{1}', BulkFormat: '{2}'-'{3}'", 
                            new object[]{BulkDir.Text,Caption.Text,BulkFormat.Text,bulkfmt}),CrmImageTrace.Sw.Info);
                    string[] files              =   GetAllServerFile(BulkDir.Text);
                    StringBuilder sb            =   new StringBuilder();
                    if (CrmImageTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update BEG COPY Server count: {0}.", files.Length), CrmImageTrace.Sw.Info);
                    foreach (string file in files)
                    {
                        Guid ImgGuid            =   Guid.NewGuid();
                        // To avoid null image names and add some formating tips
                        string ImageName        =   FormatName(displayOrder, Caption.Text, bulkfmt);
                        if ( CrmImageTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update ImageName: '{0}'", ImageName),CrmImageTrace.Sw.Info);
                        // We create the corresponding entity
                        ADNDynImage im           =   new ADNDynImage(PortalSecurity.Wrapper, ImageName);
                        im.SetOwnerFromUserId();
                        Guid EntID              =   Guid.Empty;
                        //update CRM to store new key
                        try
                        {
                            im.adn_category      =   Category;
                            EntID               =   im.Create();
                            if ( CrmImageTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update created CrmId: {0}.",EntID),CrmImageTrace.Sw.Info);
                        }
                        catch (Exception ex)
                        {
                            if ( CrmImageTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update Error adding in CRM ex: {0}",ex));
                            continue;
                        }
                        try
                        {
                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
                            SaveImage(EntID, fileInfo, thumbnailWidth, thumbnailHeight, originalWidth, originalHeight,
                               RadEditorSD.Content, RadEditorLD.Content,ImageName,Category,KeyWords.Text,
                                false, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value,
                                thumbnailResize, originalResize,ImgGuid,false);
                            //If this is a new CRMImageBook add it to the database
                            ImageDB.AddCRMImageBook(RequestEntityTypename, EntityID, ItemID, displayOrder++,MetadataXml, RadEditorSD.Content);
                            if ( CrmImageTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update added RequestEntityTypename: {0}, EntityID: {1}, displayOrder: {2}, EntID: {3}",
                                    new object[]{RequestEntityTypename,EntityID,displayOrder, EntID}),CrmImageTrace.Sw.Info);
                        }
                        catch (Exception ex)
                        {
                            if ( CrmImageTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update  EntityID: {0}, ex: {1}", EntID, ex),CrmImageTrace.Sw.Info);
                            sb.AppendFormat("{0} : [{1}]<br/>", LocalizeHelper.Localize(ImStr.ResourceFile, ImStr.ResourceItem,ImStr.PICTURES_INVALID_IMAGE_FILE, "Invalid Image File"),file);
                            continue;
                        }
                        //update CRM to store new key
                        try
                        {
                            im.adn_externalid    =   ImageDBID;
                            im.Update();
                            if ( CrmImageTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update updated Crm ImageDBID: {0}.",ImageDBID),CrmImageTrace.Sw.Info);
                        }
                        catch (Exception ex)
                        {
                            if ( CrmImageTrace.Sw.TraceError )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update Error update in CRM ex: {0}",ex));
                        }
                    }
                    if (sb.Length != 0)
                    {
                        if ( CrmImageTrace.Sw.TraceError )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update cancel errors : {0}", sb.ToString()),CrmImageTrace.Sw.Info);
                        Message.Text    =   sb.ToString();
                        e.Cancel        =   true;
                        return;
                    }
                }
                else
                {
                    if (CrmImageTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update BEG Upload Files Count: {0}.", RadUpload1.UploadedFiles.Count), CrmImageTrace.Sw.Info);
                    // Determine whether a file was uploaded
                    if ( RadUpload1.UploadedFiles.Count > 0 )
                    {
                        // To avoid null image names and add some formating tips
                        string bulkfmt          =   Server.HtmlDecode(Server.HtmlEncode(BulkFormat.Text));
                        foreach (UploadedFile fl in RadUpload1.UploadedFiles)
                        {
                            Guid ImgGuid        =   Guid.NewGuid();
                            string OrgFilename  =   string.Format("{0}_upl_{1}.{2}",RequestEntityTypename,ImgGuid,imExt);
                            //Full path of the original CRMImage
                            string physicalPath =   PathToSave + OrgFilename;
                            string ImageName    =   FormatName(0, Caption.Text, bulkfmt);
                            if ( CrmImageTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update ImageName: '{0}'", ImageName),CrmImageTrace.Sw.Info);
                            // We create the corresponding entity
                            ADNDynImage im       =   new ADNDynImage(PortalSecurity.Wrapper, ImageName);
                            im.SetOwnerFromUserId();
                            Guid EntID          =   Guid.Empty;
                            try
                            {
                                im.adn_category  =   Category;
                                EntID           =   im.Create();
                                if ( CrmImageTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update created CrmId: {0}.",EntID),CrmImageTrace.Sw.Info);
                            }
                            catch (Exception ex)
                            {
                                if ( CrmImageTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update Error adding in CRM ex: {0}",ex));
                                e.Cancel = true;
                                return;
                            }
                            try
                            {
                                // Save the CRMImage
                                fl.SaveAs(physicalPath);
                                FileInfo fileInfo = new FileInfo(physicalPath);
                                // we add the image
                                if (CrmImageTrace.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update Saving on disk and db EntityID: {0}, OrgFilename:{1}", EntID, OrgFilename), CrmImageTrace.Sw.Info);
                                SaveImage(EntID, fileInfo, thumbnailWidth, thumbnailHeight, originalWidth, originalHeight,
                                    RadEditorSD.Content, RadEditorLD.Content, ImageName,Category,KeyWords.Text,
                                    false, selFlip.SelectedItem.Value, selRotate.SelectedItem.Value,
                                    thumbnailResize, originalResize,ImgGuid, false);
                                if (CrmImageTrace.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update Saving in crm EntityID: {0}, ImageDBID:{1}", EntID, ImageDBID), CrmImageTrace.Sw.Info);
                                // copy MetadataXml
                                ImageDB.AddCRMImageBook(RequestEntityTypename, EntityID, ImageDBID, displayOrder++,MetadataXml, RadEditorSD.Content);
                            }
                            catch (Exception ex)
                            {
                                if (CrmImageTrace.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update EntityID : {0}, ex :{1}", EntID, ex), CrmImageTrace.Sw.Info);
                                //Message.Text = LocalizeHelper.Localize(ImStr.ResourceFile, ImStr.ResourceItem, ImStr.PICTURES_INVALID_IMAGE_FILE, "Invalid Image File") + "!<br/>" + flPicture.PostedFile.FileName;
                                Message.Text = LocalizeHelper.Localize(ImStr.ResourceFile, ImStr.ResourceItem, ImStr.PICTURES_INVALID_IMAGE_FILE, "Invalid Image File") + "!<br/>" + fl.FileName;
                                e.Cancel = true;
                                return;
                            }
                            /* we keep original files 
                            finally
                            {
                                System.IO.File.Delete(physicalPath);
                            }
                             * */
                            //update CRM to store new key
                            try
                            {
                                im.adn_externalid    =   ImageDBID;
                                im.Update();
                                if ( CrmImageTrace.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookAdd CRMImageBookAdd_Update updated Crm ImageDBID: {0}.",ImageDBID),CrmImageTrace.Sw.Info);
                            }
                            catch (Exception ex)
                            {
                                if ( CrmImageTrace.Sw.TraceError )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookAdd CRMImageBookAdd_Update Error update in CRM ex: {0}",ex));
                            }
                        }

                    }
                }
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]CRMImageBookAdd CRMImageBookAdd_Update END.",CrmImageTrace.Sw.Info);
            }
            else // !ShowCreate
            {
                //  update only close window ImgeBookSel.OnUpdate(e);
            }
		}

		public CRMImageBookAdd() : base(true,true,true,false)
		{
        }

        protected override void RaisePostBackEvent(System.Web.UI.IPostBackEventHandler sourceControl, string eventArgument)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect RaisePostBackEvent eventArg: {0}", eventArgument),CrmImageTrace.Sw.Info);
            base.RaisePostBackEvent(sourceControl, eventArgument);
            if (sourceControl is RadGrid)
            {
                string[] eventArgs = eventArgument.Split(':');
                ImgeBookSel.SetAction(eventArgs[0]);
            }
        }

		#region Web Form Designer generated code
        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
        /// <param name="e"></param>
        override protected void OnPreInit(EventArgs e)
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookAdd OnPreInit Begin",CrmImageTrace.Sw.Info);
            base.OnPreInit(e);
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookAdd OnPreInit End",CrmImageTrace.Sw.Info);
        }
		/// <summary>
		/// Raises OnInitEvent
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookAdd OnInit Begin",CrmImageTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookAdd OnInit End",CrmImageTrace.Sw.Info);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() 
		{    
            Load    +=  new System.EventHandler(this.Page_Load);
            Update  +=  new PageEventHandler(CRMImageBookAdd_Update);
		}

 		/// <summary>
		///  Necessary to have the traditionnal buttons automatically added to page
		/// usintg the PlaceHolders
		/// </summary>
		protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}
       #endregion
    }
}
